import socket
import sys
import logging
import psutil
from datetime import datetime
import setproctitle
import threading
import time
import os
import select


pipe_path = '/home/send_pipe'
BUF_SIZE = 10240


setproctitle.setproctitle("tcp_server")

class myThread (threading.Thread):   #继承父类threading.Thread
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name = name
        self.sock = -1

    def run(self):                   #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 
        logging.info("Starting " + self.name)

        # 打开命名管道以进行读取
        pipe_fd = os.open(pipe_path, os.O_RDONLY)
        #pipe_fd = os.open(pipe_path, os.O_RDONLY | os.O_NONBLOCK)

        try:
            while True:
                # self.sock.send("hello".encode())  # 将要传输的数据编码发送，如果是字符数据就必须要编码发送
                #self.sockock.send("hello".encode())
                data = os.read(pipe_fd, BUF_SIZE)  # 一次读取最多1024个字节
                print(data)

                if not data:
                    continue
                # 处理数据，例如打印到控制台
                logging.info(data.decode('utf-8'))  # 假设数据是UTF-8编码
                if self.sock != -1:
                    self.sock.send("hello".encode('utf-8'))
                    self.sock.send(data)


        except:
            logging.info("connection is invalid ",self.sock)
        finally:
            logging.info("finally close pipe")
            os.close(pipe_fd)

        logging.info("Exiting " + self.name)

def get_net_card():
    # 调用psutil.net_if_addrs()函数，获取所有网卡的信息
    info = psutil.net_if_addrs()
    # 遍历字典，找到"wlan0"对应的值
    for k, v in info.items():
        if k == "wlan0":
            # 遍历列表，找到地址类型为AF_INET的项
            for item in v:
                if item[0] == socket.AF_INET:
                    # 返回IP地址
                    return item[1]


def socket_service_data():
    # 连接
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(ADDR)  # 在不同主机或者同一主机的不同系统下使用实际ip
        s.listen(10)
    except socket.error as msg:
        logging.info(msg)
        sys.exit(1)

    send_thread = 0
    
    send_thread = myThread("send thread")
    send_thread.start()

    while True:
        try:
            logging.info("Wait for Connection..................")
            sock, addr = s.accept()
            logging.info("New Connection")
            
            send_thread.sock = sock

            #send_thread = myThread("send thread",sock)
            #send_thread.start()

            while True:
                try:
                    # 收
                    buf = sock.recv(BUFSIZ)  # 接收数据
                    str = buf.decode("utf-8",errors="replace")  # 解码
                    if not buf:
                        break
                    now = datetime.now()
                    # 格式化输出
                    # logging.info(now.strftime("%Y-%m-%d %H:%M:%S"))
                    logging.info(str)
                    # return buf
                    # 发
                    # buf = input("input data:")  # 输入要传输的数据
                    #if not buf:
                    #    break
                    #  sock.send(buf.encode())  # 将要传输的数据编码发送，如果是字符数据就必须要编码发送
                except socket.error as msg:
                    logging.info(msg)
                    send_thread.sock = -1
                    break
        except KeyboardInterrupt:
            logging.info('server was killed')
            socket.close()
            break

        except:
            logging.info("connect error")
            continue

        finally:
            # 关闭服务器套接字
            #socket.close()
            logging.info("finall")


if __name__ == '__main__':
    # 设置日志的格式、级别、文件名等参数
    logging.basicConfig(format="%(asctime)s %(message)s", level=logging.INFO, filename="/home/log_tcp.txt")
    # 使用logging.info函数输出内容
    # logging.info("Hello, world!")

    logging.info('\n\n---------------------------------------\n')
    logging.info('server start')

    try:
        os.mkfifo(pipe_path)
        logging.info(f"name pipe {pipe_path} created")
    except FileExistsError:
        logging.info(f"name pip {pipe_path} aready exists")

    # 调用函数
    wlan0_ip = get_net_card()

    # 初始化
    # name = socket.gethostname()

    HOST = socket.gethostbyname(wlan0_ip)  # 获取阿里云服务器私网IP，使用ifconfig可查询
    # print(HOST)
    PORT = 7000
    BUFSIZ = BUF_SIZE
    ADDR = (HOST, PORT)
    # 打印结果
    logging.info(ADDR)

    socket_service_data()
